# coding=utf-8
import pandas as pd
import json


def read_data(file_path):
    '''
    读取数据
    :param file_path:
    :return:
    '''
    try:
        return pd.read_csv(file_path)
    except Exception as e:
        print(f"Failed to read data from {file_path}: {e}")
        return None


def get_season(month):
    '''
    获取季节
    :param month:
    :return:
    '''
    seasons = ['冬', '冬', '春', '春', '春', '夏', '夏', '夏', '秋', '秋', '秋', '冬']
    return seasons[month - 1]


def process_data(df):
    '''
    处理数据
    :param df:
    :return:
    '''
    df['date_of_sale'] = pd.to_datetime(df['date_of_sale'])
    df['season'] = df['date_of_sale'].dt.month.map(get_season)

    season_data = df['season'].value_counts().to_dict()

    average_prices = df.groupby(['item_id', 'item_name'])['sales_unit_price'].mean().reset_index(name='mean_price')

    return season_data, average_prices


def write_data(season_data, average_prices, season_file_path, average_prices_file_path):
    '''
    写入数据
    :param season_data:
    :param average_prices:
    :param season_file_path:
    :param average_prices_file_path:
    :return:
    '''
    try:
        with open(season_file_path, 'w', encoding='utf-8') as f:
            json.dump(season_data, f, ensure_ascii=False, indent=4)
        average_prices.to_excel(average_prices_file_path, index=False)
    except Exception as e:
        print(f"Failed to write data: {e}")


# 路径和文件名
data_file_path = '../static/data/data.csv'
season_file_path = '../static/data/season.json'
average_prices_file_path = 'average_prices.xlsx'

# 读取和处理数据
df = read_data(data_file_path)
if df is not None:
    season_data, average_prices = process_data(df)
    write_data(season_data, average_prices, season_file_path, average_prices_file_path)
